export function nanToZero(n:number) {
  return isNaN(n) ? 0 : n
}

export function lastValidIndex(ns:number[]):number {
  const i = ns.length - 1
  const last = ns[i]
  const lefts = ns.slice(0, -1)
  return last === undefined ? NaN : isNaN(last) ? lastValidIndex(lefts) : i
}

export function lastValidScore(ns:number[]): number {
  const i = lastValidIndex(ns)
  return isNaN(i) ? NaN : ns[i]
}

export function lastSecondValidScore(ns:number[]): number {
  const i = lastValidIndex(ns)
  if (isNaN(i)) {
    return NaN
  }
  const lefts = ns.slice(0, i)
  return lastValidScore(lefts)
}

/**
 * Sum all score record
 * Example:
 *  softballSum(['5', '2', 'C', 'D', '+']) === 30
 *  softballSum(['5', '-2', '4', 'C', 'D', '9', '+', '+']) === 27
 * @param scores record array, like ['5', '2', 'C', 'D', '+']
 * @returns result sum scores
 */
export function softballSum(scores: string[]): number {
  const intScores = scores.reduce((numScores: number[], b, i, tmps) => {
    console.debug(numScores, b, i, tmps)
    let n = NaN
    if (b === 'C') {
      numScores[i -1] = NaN
    } else if (b === 'D') {
      n = lastValidScore(numScores) * 2
    } else if (b === '+') {
      n = lastValidScore(numScores) + lastSecondValidScore(numScores)
    } else {
      n = parseInt(b)
    }
    numScores.push(n)
    return numScores
  }, [])
  return intScores.reduce((a: number, b: number) => nanToZero(a) + nanToZero(b))
}
